<template>
  <div class="theory-page">
    <!-- 顶部标题区域 -->
    <div class="page-header mb-6">
      <h2 class="title">理论知识管理</h2>
      <p class="desc">管理焊接相关的理论知识内容，支持PDF、视频和网页链接</p>
    </div>

    <!-- 搜索与操作区 -->
    <el-card class="search-card mb-6">
      <div class="search-container">
        <el-row :gutter="24">
          <!-- 搜索与筛选 -->
          <el-col :span="24">
            <el-row :gutter="24">
              <el-col :span="10">
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="搜索标题"
                  prefix-icon="el-icon-search"
                  clearable
                  @keyup.enter.native="handleSearch"
                ></el-input>
              </el-col>
              <el-col :span="3" style="min-width: 160px;">
                <el-select
                  v-model="searchForm.category"
                  placeholder="所有分类"
                  clearable
                >
                  <el-option
                    v-for="item in categoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-col>
              <!-- <el-col :span="3" style="min-width: 160px;">
                <el-select
                  v-model="searchForm.type"
                  placeholder="所有类型"
                  clearable
                >
                  <el-option label="PDF文件" value="pdf"></el-option>
                  <el-option label="视频" value="video"></el-option>
                  <el-option label="网页链接" value="link"></el-option>
                </el-select>
              </el-col> -->
              <el-col :span="4" style="min-width: 200px;">
                <el-button 
                  type="primary"
                  icon="el-icon-search"
                  @click="handleSearch"
                >
                  搜索
                </el-button>
                <el-button 
                  @click="handleReset"
                >
                  重置
                </el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 理论知识列表 -->
    <el-card>
      <div class="table-header">
        <el-button 
          type="primary" 
          icon="el-icon-plus"
          @click="openTheoryModal()"
          size="medium"
        >
          添加理论知识
        </el-button>
      </div>
      <el-table
        :data="theoryList"
        v-loading="loading"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <!-- 序号列 -->
        <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
        ></el-table-column>

        <!-- 分类列 -->
        <el-table-column
          prop="category"
          label="分类"
          min-width="120"
        ></el-table-column>

        <!-- 标题列 -->
        <el-table-column
          prop="title"
          label="标题"
          min-width="200"
        ></el-table-column>

        <!-- 状态列 -->
        <el-table-column
          label="状态"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" size="small">
              {{ scope.row.status === 1 ? '正常' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 内容类型列 -->
        <el-table-column
          label="内容类型"
          min-width="140"
          align="center"
        >
          <template slot-scope="scope">
            <el-tag
              :class="['content-tag', `content-tag-${scope.row.type}`]"
              size="small"
            >
              <i :class="typeIconMap[scope.row.type]"></i>
              <span>{{ typeLabelMap[scope.row.type] }}</span>
            </el-tag>
          </template>
        </el-table-column>

        <!-- 创建时间列 -->
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="140"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime | formatDate }}
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          min-width="140"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="openTheoryModal(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="small"
              :style="{ color: scope.row.status == 1 ? '#F53F3F' : '#00B42A' }"
              @click="handleDisable(scope.row)"
            >
              {{ scope.row.status == 1 ? '停用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.page"
          :page-sizes="[10, 20, 50]"
          :page-size="pagination.size"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑理论知识模态框 -->
    <el-drawer
      :title="modalTitle"
      :visible.sync="theoryModalVisible"
      direction="rtl"
      :size="750"
      :close-on-click-modal="false"
      class="theory-drawer"
    >
      <div style="padding: 20px;">
        <el-form
          ref="theoryForm"
          :model="formData"
          :rules="formRules"
          label-width="100px"
          class="modal-form"
        >
          <el-row :gutter="20">
            <!-- 分类输入 -->
            <el-col :span="12">
              <el-form-item label="分类" prop="categoryId">
                <el-select
                  v-model="formData.categoryId"
                  placeholder="选择或输入分类"
                  clearable
                  filterable
                  allow-create
                  default-first-option
                  style="width: 100%;"
                >
                  <el-option
                    v-for="item in categoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
                <p class="form-hint">选择已有分类或输入新分类</p>
              </el-form-item>
            </el-col>

            <!-- 内容类型选择 -->
            <el-col :span="12">
              <el-form-item label="内容类型" prop="type">
                <el-select
                  v-model="formData.type"
                  placeholder="请选择内容类型"
                  @change="handleTypeChange"
                  style="width: 100%;"
                >
                  <el-option label="PDF文件" value="pdf">
                    <i class="el-icon-document"></i> PDF文件
                  </el-option>
                  <el-option label="视频" value="video">
                    <i class="el-icon-video-camera"></i> 视频
                  </el-option>
                  <el-option label="网页链接" value="link">
                    <i class="el-icon-link"></i> 网页链接
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <!-- 标题输入 -->
            <el-col :span="24">
              <el-form-item label="标题" prop="title">
                <el-input 
                  v-model="formData.title" 
                  placeholder="请输入理论知识标题"
                  maxlength="100"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>

            <!-- PDF内容区域 -->
            <el-col :span="24" v-if="formData.type === 'pdf'">
              <el-form-item
                label="PDF文件"
              >
                <el-upload
                  class="upload-demo"
                  action=""
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  :on-remove="handleFileRemove"
                  accept=".pdf"
                  :file-list="pdfFileList"
                  multiple
                  :limit="5"
                >
                  <el-button size="medium" type="primary" icon="el-icon-upload">
                    选择文件
                  </el-button>
                  <div slot="tip" class="el-upload__tip">
                    支持格式：PDF，最多上传5个文件，单个文件不超过10MB
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>

            <!-- 视频内容区域 -->
            <el-col :span="24" v-if="formData.type === 'video'">
              <el-form-item label="视频文件">
                <el-upload
                  class="upload-demo"
                  action=""
                  :auto-upload="false"
                  :on-change="handleVideoFileChange"
                  :on-remove="handleVideoFileRemove"
                  accept=".mp4,.avi,.mov,.wmv"
                  :file-list="videoFileList"
                  multiple
                  :limit="3"
                >
                  <el-button size="medium" type="primary" icon="el-icon-upload">
                    选择视频文件
                  </el-button>
                  <div slot="tip" class="el-upload__tip">
                    支持格式：MP4、AVI、MOV、WMV，最多上传3个文件，单个文件不超过100MB
                  </div>
                </el-upload>
              </el-form-item>
              
              <el-form-item label="或视频链接" prop="videoUrl">
                <el-input 
                  v-model="formData.videoUrl" 
                  placeholder="输入视频链接（例如: https://example.com/video.mp4）"
                  clearable
                >
                  <i slot="prefix" class="el-icon-link"></i>
                </el-input>
                <p class="form-hint">可以上传视频文件或填写视频链接，至少选择一项</p>
              </el-form-item>
            </el-col>

            <!-- 链接内容区域 -->
            <el-col :span="24" v-if="formData.type === 'link'">
              <el-form-item
                prop="linkUrl"
                label="网页链接"
              >
                <el-input 
                  v-model="formData.linkUrl" 
                  placeholder="请输入网页链接地址（例如: https://example.com）"
                  clearable
                >
                  <i slot="prefix" class="el-icon-link"></i>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div style="text-align: right; margin-top: 30px; padding-top: 20px; border-top: 1px solid #EBEEF5;">
          <el-button @click="theoryModalVisible = false" size="medium">取消</el-button>
          <el-button type="primary" @click="saveTheory" size="medium">
            {{ modalTitle.includes('编辑') ? '保存修改' : '创建' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import api from '@/api';

export default {
  data() {
    return {
      // 搜索表单
      searchForm: {
        keyword: '',
        category: '',
        type: '',
        status: ''
      },

      // 加载状态
      loading: false,

      // 分类列表
      categoryList: [],

      // 理论知识列表数据
      theoryList: [],

      // 分页配置
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },

      // 模态框状态
      theoryModalVisible: false,
      modalTitle: '添加理论知识',

      // 表单数据
      formData: {
        id: '',
        category: '',
        title: '',
        type: '',
        pdfFile: null,
        videoUrl: '',
        linkUrl: ''
      },

      // 文件列表
      pdfFileList: [],
      videoFileList: [],
      
      // 上传后的文件URL
      uploadedPdfUrls: [],
      uploadedVideoUrls: [],
      
      // 上传状态
      uploadingPdf: false,
      uploadingVideo: false,

      // 类型映射（图标和标签）
      typeLabelMap: {
        pdf: 'PDF文件',
        video: '视频',
        link: '网页链接'
      },
      typeIconMap: {
        pdf: 'el-icon-document',
        video: 'el-icon-video-camera',
        link: 'el-icon-link'
      },

      // 表单验证规则
      formRules: {
        categoryId: [
          { required: true, message: '请选择或输入分类', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 2, max: 100, message: '标题长度在2-100个字符之间', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择内容类型', trigger: 'change' }
        ],
        linkUrl: [
          { required: true, message: '请输入网页链接', trigger: 'blur' },
          { type: 'url', message: '请输入正确的网址', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    // 加载理论知识列表和分类
    this.getTheoryList();
    this.getCategories();
  },
  methods: {
    // 获取理论知识列表
    async getTheoryList() {
      try {
        this.loading = true;
        const params = {
          page: this.pagination.page,
          page_size: this.pagination.size
        };
        
        // 添加搜索参数
        if (this.searchForm.keyword) {
          params.title = this.searchForm.keyword;
        }
        if (this.searchForm.category) {
          params.category_id = this.searchForm.category;
        }
        if (this.searchForm.status !== '') {
          params.status = this.searchForm.status;
        }
        
        const res = await api.theory.getTheoryList(params);
        
        if (res && res.code === 200) {
          // 兼容两种返回格式
          const list = Array.isArray(res.data?.list) ? res.data.list : (Array.isArray(res.data) ? res.data : []);
          
          this.theoryList = list.map(item => ({
            id: item.id,
            categoryId: item.category?.id || item.category_id || '',
            category: item.category?.name || item.category_name || '',
            title: item.title || '',
            type: this.mapBackendType(item.type), // 映射后端类型 1/2/3 到前端 pdf/video/link
            fileUrl: this.parseFileUrl(item.file_url), // 解析文件URL(处理双重JSON编码)
            thirdPartyLink: item.third_party_link || '',
            status: item.status,
            createTime: item.created_at || ''
          }));
          
          // 兼容两种分页格式
          if (res.pagination) {
            this.pagination.total = res.pagination.total || 0;
            this.pagination.page = res.pagination.page || this.pagination.page;
            this.pagination.size = res.pagination.page_size || this.pagination.size;
          } else if (res.data) {
            this.pagination.total = res.data.total || 0;
            this.pagination.page = res.data.page || this.pagination.page;
            this.pagination.size = res.data.page_size || this.pagination.size;
          }
        }
      } catch (error) {
        this.$message.error('获取理论知识列表失败');
      } finally {
        this.loading = false;
      }
    },

    // 获取分类列表
    async getCategories() {
      try {
        const res = await api.theory.getKnowledgeCategories();
        if (res && res.code === 200) {
          const list = Array.isArray(res.data?.list) ? res.data.list : (Array.isArray(res.data) ? res.data : []);
          // 修复Bug1: 正确映射分类列表,保留id和name
          this.categoryList = list.map(item => {
            if (typeof item === 'string') {
              return { id: item, name: item };
            }
            return {
              id: item.id,
              name: item.name || item.category_name || item.id
            };
          });
        }
      } catch (error) {
      }
    },

    // 解析文件URL(处理多重JSON编码)
    parseFileUrl(fileUrl) {
      if (!fileUrl) return [];
      
      // 如果已经是数组,直接返回
      if (Array.isArray(fileUrl)) {
        // 清理数组中的每个URL
        return fileUrl.map(url => this.cleanUrl(url)).filter(url => url);
      }
      
      // 如果是字符串,尝试递归解析
      if (typeof fileUrl === 'string') {
        try {
          let parsed = fileUrl;
          
          // 递归解析,直到不再是字符串或无法解析
          while (typeof parsed === 'string') {
            try {
              const temp = JSON.parse(parsed);
              parsed = temp;
            } catch (e) {
              // 无法继续解析,退出循环
              break;
            }
          }
          
          // 如果解析结果是数组,清理并返回
          if (Array.isArray(parsed)) {
            return parsed.map(url => this.cleanUrl(url)).filter(url => url);
          }
          
          // 如果解析结果是单个字符串,清理后包装成数组
          if (typeof parsed === 'string') {
            const cleanedUrl = this.cleanUrl(parsed);
            return cleanedUrl ? [cleanedUrl] : [];
          }
          
          return [];
        } catch (e) {
          // 如果解析失败,尝试清理后作为单个URL处理
          const cleanedUrl = this.cleanUrl(fileUrl);
          return cleanedUrl ? [cleanedUrl] : [];
        }
      }
      
      return [];
    },

    // 清理URL字符串(去除多余的引号、方括号、转义字符等)
    cleanUrl(url) {
      if (!url || typeof url !== 'string') return '';
      
      // 去除首尾空格
      let cleaned = url.trim();
      
      // 去除首尾的引号和方括号
      cleaned = cleaned.replace(/^[\["\]]+|[\]"\[]+$/g, '');
      
      // 替换转义的反斜杠
      cleaned = cleaned.replace(/\\\\/g, '/');
      
      // 去除多余的反斜杠
      cleaned = cleaned.replace(/\\/g, '');
      
      return cleaned.trim();
    },

    // 映射后端类型到前端类型
    mapBackendType(type) {
      const typeMap = {
        1: 'pdf',
        2: 'video',
        3: 'link'
      };
      return typeMap[type] || 'pdf';
    },

    // 映射前端类型到后端类型
    mapFrontendType(type) {
      const typeMap = {
        'pdf': 1,
        'video': 2,
        'link': 3
      };
      return typeMap[type] || 1;
    },

    // 搜索功能
    handleSearch() {
      this.pagination.page = 1;
      this.getTheoryList();
    },

    // 重置功能
    handleReset() {
      this.searchForm = {
        keyword: '',
        category: '',
        type: '',
        status: ''
      };
      this.pagination.page = 1;
      this.getTheoryList();
    },

    // 打开理论知识模态框(新增/编辑)
    openTheoryModal(row) {
      // 重置表单
      this.$refs.theoryForm && this.$refs.theoryForm.resetFields();
      
      // 清空文件列表和上传的URL
      this.pdfFileList = [];
      this.videoFileList = [];
      this.uploadedPdfUrls = [];
      this.uploadedVideoUrls = [];
      
      if (row) {
        // 编辑模式
        this.modalTitle = '编辑理论知识';
        this.formData = { 
          ...row,
          categoryId: row.categoryId || row.category_id || row.category || ''
        };
        
        // 处理文件和链接的回显
        if (row.type === 'pdf') {
          // PDF文件回显 - 确保fileUrl是数组
          const fileUrls = Array.isArray(row.fileUrl) ? row.fileUrl : (row.fileUrl ? [row.fileUrl] : []);
          if (fileUrls.length > 0) {
            this.uploadedPdfUrls = [...fileUrls];
            this.pdfFileList = fileUrls.map((url, index) => {
              // 从URL中提取文件名
              const fileName = url.split('/').pop() || `文件${index + 1}.pdf`;
              return {
                name: decodeURIComponent(fileName),
                url: url,
                uid: Date.now() + index
              };
            });
          }
        } else if (row.type === 'video') {
          // 视频文件回显 - 确保fileUrl是数组
          const fileUrls = Array.isArray(row.fileUrl) ? row.fileUrl : (row.fileUrl ? [row.fileUrl] : []);
          if (fileUrls.length > 0) {
            this.uploadedVideoUrls = [...fileUrls];
            this.videoFileList = fileUrls.map((url, index) => {
              // 从URL中提取文件名
              const fileName = url.split('/').pop() || `视频${index + 1}`;
              return {
                name: decodeURIComponent(fileName),
                url: url,
                uid: Date.now() + index
              };
            });
          }
          // 视频链接回显
          this.formData.videoUrl = row.thirdPartyLink || '';
        } else if (row.type === 'link') {
          // 网页链接回显
          this.formData.linkUrl = row.thirdPartyLink || '';
        }
      } else {
        // 新增模式
        this.modalTitle = '添加理论知识';
        this.formData = {
          id: '',
          categoryId: '',
          title: '',
          type: '',
          pdfFile: null,
          videoUrl: '',
          linkUrl: ''
        };
      }
      this.theoryModalVisible = true;
    },

    // 内容类型切换
    handleTypeChange(type) {
      // 切换类型时清空其他类型的内容
      this.formData.pdfFile = null;
      this.formData.videoUrl = '';
      this.formData.linkUrl = '';
      this.pdfFileList = [];
      this.videoFileList = [];
      this.uploadedPdfUrls = [];
      this.uploadedVideoUrls = [];
    },

    // PDF文件上传变化 - 立即上传
    async handleFileChange(file, fileList) {
      this.pdfFileList = fileList;
      
      // 只处理新添加的文件(状态为ready)
      if (file.status === 'ready' && file.raw) {
        this.uploadingPdf = true;
        try {
          const formData = new FormData();
          formData.append('type', '1'); // 1=PDF
          formData.append('files[]', file.raw);
          
          const uploadRes = await api.theory.uploadKnowledgeFile(formData);
          if (uploadRes && uploadRes.code === 200) {
            // 解析上传返回的URL - 支持多种返回格式
            const urls = Array.isArray(uploadRes.data) ? uploadRes.data : 
                        (uploadRes.data.urls || uploadRes.data.file_urls || [uploadRes.data]);
            
            if (urls.length > 0) {
              this.uploadedPdfUrls.push(...urls);
              this.$message.success('PDF文件上传成功');
            } else {
              throw new Error('未返回文件URL');
            }
          } else {
            this.$message.error('PDF文件上传失败');
            // 移除上传失败的文件
            const index = this.pdfFileList.findIndex(f => f.uid === file.uid);
            if (index > -1) {
              this.pdfFileList.splice(index, 1);
            }
          }
        } catch (error) {
          this.$message.error('PDF文件上传失败');
          // 移除上传失败的文件
          const index = this.pdfFileList.findIndex(f => f.uid === file.uid);
          if (index > -1) {
            this.pdfFileList.splice(index, 1);
          }
        } finally {
          this.uploadingPdf = false;
        }
      }
    },

    // PDF文件移除
    handleFileRemove(file, fileList) {
      this.pdfFileList = fileList;
      // 同时移除对应的URL
      if (this.uploadedPdfUrls.length > 0) {
        this.uploadedPdfUrls.pop();
      }
    },

    // 视频文件上传变化 - 立即上传
    async handleVideoFileChange(file, fileList) {
      this.videoFileList = fileList;
      
      // 只处理新添加的文件(状态为ready)
      if (file.status === 'ready' && file.raw) {
        this.uploadingVideo = true;
        try {
          const formData = new FormData();
          formData.append('type', '2'); // 2=视频
          formData.append('files[]', file.raw);
          
          const uploadRes = await api.theory.uploadKnowledgeFile(formData);
          if (uploadRes && uploadRes.code === 200) {
            // 解析上传返回的URL - 支持多种返回格式
            const urls = Array.isArray(uploadRes.data) ? uploadRes.data : 
                        (uploadRes.data.urls || uploadRes.data.file_urls || [uploadRes.data]);
            
            if (urls.length > 0) {
              this.uploadedVideoUrls.push(...urls);
              this.$message.success('视频文件上传成功');
            } else {
              throw new Error('未返回文件URL');
            }
          } else {
            this.$message.error('视频文件上传失败');
            // 移除上传失败的文件
            const index = this.videoFileList.findIndex(f => f.uid === file.uid);
            if (index > -1) {
              this.videoFileList.splice(index, 1);
            }
          }
        } catch (error) {
          this.$message.error('视频文件上传失败');
          // 移除上传失败的文件
          const index = this.videoFileList.findIndex(f => f.uid === file.uid);
          if (index > -1) {
            this.videoFileList.splice(index, 1);
          }
        } finally {
          this.uploadingVideo = false;
        }
      }
    },

    // 视频文件移除
    handleVideoFileRemove(file, fileList) {
      this.videoFileList = fileList;
      // 同时移除对应的URL
      if (this.uploadedVideoUrls.length > 0) {
        this.uploadedVideoUrls.pop();
      }
    },

    // 保存理论知识
    async saveTheory() {
      this.$refs.theoryForm.validate(async valid => {
        if (valid) {
          try {
            // 验证文件已上传
            if (this.formData.type === 'pdf' && this.uploadedPdfUrls.length === 0 && !this.formData.id) {
              this.$message.warning('请至少上传一个PDF文件');
              return;
            }
            
            if (this.formData.type === 'video' && this.uploadedVideoUrls.length === 0 && !this.formData.videoUrl && !this.formData.id) {
              this.$message.warning('请上传视频文件或填写视频链接');
              return;
            }

            let fileUrls = [];
            
            // 使用已上传的文件URL
            if (this.formData.type === 'pdf' && this.uploadedPdfUrls.length > 0) {
              fileUrls = this.uploadedPdfUrls;
            }
            
            if (this.formData.type === 'video' && this.uploadedVideoUrls.length > 0) {
              fileUrls = this.uploadedVideoUrls;
            }
            
            // 如果是视频链接,使用输入的链接
            if (this.formData.type === 'video' && this.formData.videoUrl && this.uploadedVideoUrls.length === 0) {
              fileUrls = [this.formData.videoUrl];
            }

            // 构建提交数据,支持category_id和category双字段
            const submitData = {
              title: this.formData.title,
              type: this.mapFrontendType(this.formData.type), // 转换为后端类型: pdf->1, video->2, link->3
              status: 1
            };

            // 根据categoryId的类型判断是已有分类还是新分类
            const existingCategory = this.categoryList.find(c => c.id === this.formData.categoryId);
            if (existingCategory) {
              // 选择已有分类: 传category_id
              submitData.category_id = this.formData.categoryId;
            } else if (this.formData.categoryId) {
              // 输入新分类: 传category字符串
              submitData.category = this.formData.categoryId;
            }

            // 根据类型设置不同字段
            if (this.formData.type === 'link') {
              submitData.third_party_link = this.formData.linkUrl;
            } else if (fileUrls.length > 0) {
              submitData.file_url = fileUrls;
            }

            // 新增或编辑
            if (this.formData.id) {
              submitData.id = this.formData.id;
              await api.theory.updateTheory(submitData);
              this.$message.success('编辑理论知识成功');
            } else {
              await api.theory.createTheory(submitData);
              this.$message.success('新增理论知识成功');
            }

            this.theoryModalVisible = false;
            this.getTheoryList(); // 刷新列表
            this.getCategories(); // 刷新分类列表
            
          } catch (error) {
            this.$message.error(error.message || '保存失败');
          }
        }
      });
    },

    // 停用/启用理论知识
    async handleDisable(row) {
      const updateStatusName = row.status == 1 ? '停用' : '启用';
      
      try {
        await this.$confirm(`确定要${updateStatusName}《${row.title}》吗？`, '提示', {
          type: 'warning'
        });

        await api.theory.updateTheory({
          ...row,
          ...{status: row.status == 1 ? 0 : 1, file_url: row.fileUrl, type: this.mapFrontendType(row.type)}
        });
        
        this.$message.success(`${updateStatusName}成功`);
        this.getTheoryList(); // 刷新列表
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(`${updateStatusName}失败`);
        }
      }
    },

    // 分页相关方法
    handleSizeChange(size) {
      this.pagination.size = size;
      this.pagination.page = 1;
      this.getTheoryList();
    },
    handleCurrentChange(page) {
      this.pagination.page = page;
      this.getTheoryList();
    }
  }
};
</script>

<style scoped>
/* 页面标题 */
.page-header {
  margin-bottom: 20px;
  text-align: left;
}
.title {
  font-size: 20px;
  font-weight: bold;
  color: #304156;
  margin-bottom: 5px;
  margin-left: 0;
}
.desc {
  color: #86909C;
  font-size: 14px;
  text-align: left;
}

/* 搜索区 */
.search-card {
  padding: 15px 20px;
}
.search-container {
  width: 100%;
}

/* 表格头部 */
.table-header {
  margin-bottom: 16px;
  text-align: left;
}

/* 内容类型标签样式 */
.content-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}
.content-tag-pdf {
  background-color: #FEE2E2;
  color: #DC2626;
  border-color: #FEE2E2;
}
.content-tag-video {
  background-color: #F3E8FF;
  color: #7C3AED;
  border-color: #F3E8FF;
}
.content-tag-link {
  background-color: #D1FAE5;
  color: #059669;
  border-color: #D1FAE5;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 模态框表单 */
.modal-form {
  margin-top: 10px;
}

/* 表单提示 */
.form-hint {
  margin-top: 5px;
  font-size: 12px;
  color: #86909C;
  line-height: 1.4;
}

/* 上传组件样式 */
.upload-demo {
  width: 100%;
}

/* 抽屉样式 */
.theory-drawer {
  --drawer-padding: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-container .el-row {
    flex-direction: column;
    gap: 10px;
  }
}
</style>